﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;

namespace Aribaccio.Custom
{
    public class PasswordBoxAttached
    {
        private static bool _IsUpdating = false;
        public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxAttached), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));
        public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordBoxAttached), new FrameworkPropertyMetadata(default(bool), new PropertyChangedCallback(OnAttachChanged)));

        public static bool GetAttach(DependencyObject d)
        {
            return (bool)d.GetValue(AttachProperty);
        }

        public static void SetAttach(DependencyObject d, bool value)
        {
            d.SetValue(AttachProperty, value);
        }

        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = (PasswordBox)d;
            passwordBox.PasswordChanged -= Passwor_PasswordChanged;
            if (!_IsUpdating)
            {
                passwordBox.Password = e.NewValue?.ToString();
            }
            passwordBox.PasswordChanged += Passwor_PasswordChanged;
        }

        private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = (PasswordBox)d;
            passwordBox.PasswordChanged += Passwor_PasswordChanged;
        }

        private static void Passwor_PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = (PasswordBox)sender;
            _IsUpdating = true;
            SetPassword(passwordBox, passwordBox.Password);
            _IsUpdating = false;
        }

        public static string? GetPassword(DependencyObject d)
        {
            return d.GetValue(PasswordProperty).ToString();
        }

        public static void SetPassword(DependencyObject d, string value)
        {
            d.SetValue(PasswordProperty, value);
        }


    }
}
